//封装 axios请求前置后置拦截处理
import axios from "axios" //axios
import router from "../router" //router
import { Notification, MessageBox, Message } from 'element-ui' //element-ui 弹窗样式
import store from '@/store' //全局状态管理
import errorCode from "@/utils/errorCode" //错误码以及信息

//默认请求头
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

//axios实例
const service = axios.create({
    //请求url中的公共部分
    // baseURL: 'http://localhost:8081',
    baseURL: 'http://192.168.193.14:8081', //虚拟机docker 端口
    //请求超时时间 毫秒
    timeout: 5000
})

//请求拦截器 request
service.interceptors.request.use(config => {
        //登录成功后会从后端获取token并存入localStorage（本地储存）里，在后续的每次请求都携带token，后端拿到token，验证token正确才会执行相应的操作
        config.headers['Authorization'] = localStorage.getItem("token"); //让每个请求都需要携带token

        // get请求映射params参数
        if (config.method === 'get' && config.params) {
            let url = config.url + '?';
            for (const propName of Object.keys(config.params)) {
                const value = config.params[propName];
                var part = encodeURIComponent(propName) + "=";
                if (value !== null && typeof(value) !== "undefined") {
                    if (typeof value === 'object') {
                        for (const key of Object.keys(value)) {
                            let params = propName + '[' + key + ']';
                            var subPart = encodeURIComponent(params) + "=";
                            url += subPart + encodeURIComponent(value[key]) + "&";
                        }
                    } else {
                        url += part + encodeURIComponent(value) + "&";
                    }
                }
            }
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }

        return config;
    }, error => {
        console.log(error)
        Promise.reject(error)
    })
    //响应拦截器 response
service.interceptors.response.use(res => {

        //未设置状态码则默认为200 成功
        const code = res.data.code || 200;
        //未登录并且没权限
        if (code === 401) {
            Message({
                    message: '登录状态已过期,请重新登录！',
                    type: 'info',
                })
                //用户登出
                //清除localStorage内容
            localStorage.clear();
            //清除session
            sessionStorage.clear();
            //清除全局状态存入的信息
            store.commit("resetState");
            store.commit("resetUserInfo");
            //跳转到登录
            router.push("/login");

            //其他非成功状态码
        } else if (code != 200) {
            Message.error(res.data.msg ? res.data.msg : '系统异常！')
            return Promise.reject(res.data.msg);
            //200 成功 直接返回响应结果
        } else {
            return res;
        }
    },
    //响应状态错误时回调
    error => {
        console.log('err' + error)
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    })
export default service